# forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError

User = get_user_model()


class RegisterForm(forms.ModelForm):
    password = forms.CharField(
        label="密码",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请输入密码'}),
        min_length=6,
        error_messages={'min_length': '密码长度不能少于6位'}
    )
    confirm_password = forms.CharField(
        label="确认密码",
        widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder': '请再次输入密码'}),
    )

    class Meta:
        model = User
        fields = ('username', 'nickname')
        widgets = {
            'username': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入用户名'}),
            'nickname': forms.TextInput(attrs={'class': 'form-control', 'placeholder': '请输入昵称'}),
        }
        labels = {
            'username': '用户名',
            'nickname': '昵称',
        }

    def clean(self):
        cleaned_data = super().clean()
        password = cleaned_data.get('password')
        confirm_password = cleaned_data.get('confirm_password')

        # 验证密码是否匹配
        if password and confirm_password and password != confirm_password:
            raise ValidationError({'confirm_password': '两次密码输入不一致'})

        # 验证用户名是否已存在
        username = cleaned_data.get('username')
        if username and User.objects.filter(username=username).exists():
            raise ValidationError({'username': '该用户名已被注册'})

        return cleaned_data

    def save(self, commit=True):
        user = super().save(commit=False)
        user.set_password(self.cleaned_data['password'])
        if commit:
            user.save()
        return user